﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;

namespace BgTransAPI.ControllerHelpers
{
    public class CaptchaDecoder
    {
        private readonly string imageUrl;

        public CaptchaDecoder(string imageUrl)
        {
            this.imageUrl = imageUrl;
        }

        private Image GetImage(CookieContainer cookie)
        {
            var request = WebRequest.Create(this.imageUrl) as HttpWebRequest;
            request.ContentType = "image/JPEG";
            request.Method = "GET";
            request.CookieContainer = cookie;

            var response = request.GetResponse();
           
            Image img = Image.FromStream(response.GetResponseStream());

            return img;
        }

        private string SaveImageToHard(Image img)
        {
            string path = Path.GetTempPath() + "\\Captcha.jpg";
            img.Save(path, ImageFormat.Jpeg);
            return path;
        }

        public string DecodeJpgImage(CookieContainer cookie) 
        { 
            var img = GetImage(cookie);
            string filePath = SaveImageToHard(img);

            //OCR Operations ... 
            MODI.Document md = new MODI.Document(); 
            md.Create(filePath); 
            md.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true); 
            MODI.Image image = (MODI.Image)md.Images[0];

            File.Delete(filePath);
            
            string decodeImageAsString = image.Layout.Text.Trim();
            return decodeImageAsString;
        }
    }
}